import 'package:flutter/material.dart';
import 'package:flutter/physics.dart';

class PhysicsCardDragDemo extends StatelessWidget {
  const PhysicsCardDragDemo({super.key});
  static const String routeName = 'misc/physics_card';

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Spring Physics')),
      body: DraggableCard(child: FlutterLogo(size: 128)),
    );
  }
}

class DraggableCard extends StatefulWidget {
  const DraggableCard({super.key, required this.child});
  final Widget child;

  @override
  State<DraggableCard> createState() => _DraggableCardState();
}

class _DraggableCardState extends State<DraggableCard>
    with SingleTickerProviderStateMixin {
  late final AnimationController _controller;
  // 表示card在被拖拽或在执行动画效果时的对齐方式
  //
  // 当正在被拖拽时，其值由GestureDetector的onPanUpdate回调方法计算确定。
  // 如果正在执行动画效果，其值被放入_animation对象中
  var _dragAlignment = Alignment.center;
  late Animation<Alignment> _animation;
  final _spring = const SpringDescription(
    mass: 10,
    stiffness: 1000,
    damping: 0.7,
  );
  // 由animation controller调用，用于计算与分辨率相关的相对速度
  double _normalizeVelocity(Offset velocity, Size size) {
    final normalizedVelocity = Offset(
      velocity.dx / size.width,
      velocity.dy / size.height,
    );

    // 返回负值表示从中心拖拽离开
    return -normalizedVelocity.distance;
  }

  // 计算并运行一个 [SpringSimulation]
  void _runAnimation(Offset velocity, Size size) {
    _animation = _controller.drive(
      AlignmentTween(begin: _dragAlignment, end: Alignment.center),
    );
    final simulation = SpringSimulation(
      _spring,
      0,
      1,
      _normalizeVelocity(velocity, size),
    );
    _controller.animateWith(simulation);
  }

  @override
  void initState() {
    super.initState();
    _controller = AnimationController.unbounded(vsync: this)
      ..addListener(
        () => setState(() {
          _dragAlignment = _animation.value;
        }),
      );
  }

  @override
  void dispose() {
    super.dispose();
    _controller.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final size = MediaQuery.of(context).size;
    return GestureDetector(
      onPanStart: (details) => _controller.stop(canceled: true),
      onPanUpdate: (details) => setState(() {
        _dragAlignment += Alignment(
          details.delta.dx / (size.width / 2),
          details.delta.dy / (size.height / 2),
        );
      }),
      onPanEnd: (details) => _runAnimation(details.velocity.pixelsPerSecond, size),
      child: Align(
        alignment: _dragAlignment,
        child: Card(child: widget.child,),
      ),
    );
  }
}
